from django.conf import settings
from django.core.files.storage import Storage
from fdfs_client.client import Fdfs_client
from django.utils.deconstruct import deconstructible


@deconstructible()
class FastDFSStorage(Storage):

    def __init__(self, conf_client=None, base_url=None):
        if not conf_client:
            conf_client = settings.CLIENT_CONFIG
        self.conf_client = conf_client

        if not base_url:
            base_url = settings.BASE_URL
        self.base_url = base_url

    def _open(self, name, mode='rb'):
        pass

    def _save(self, name, content):
        # 文件保存
        # 建立fdfs连接
        client = Fdfs_client(self.conf_client)
        ret = client.upload_by_buffer(content.read())
        # 判断文件是否上传成功
        if ret['Status'] != 'Upload successed.':
            raise Exception("upload file failed")
        # 获取文件唯一标识
        file_name = ret['Remote file_id']

        return file_name

    def url(self, name):
        # 拼接完整路径
        return self.base_url + name

    def exists(self, name):

        return False